/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package org.foment.gem.statistic;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.DateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Iterator;
import org.foment.joliage3.sql.Database;

/**
 *
 * @author Dusan
 */
public class Employee
{
    
    // Ime i vrednost atributa iz baze za zaposlenog
    private HashMap<String, String> _values = new HashMap<String, String>();
    private int _employeeId;
    private boolean _satisfyCondition = true;

    // lista svih zaposlenih preuzetih iz baze.
    public static ArrayList<Employee> _employees = new ArrayList<Employee>();
    // ovde se nalaze atributi koje inicijalno uzimamo iz baze.
    private static final String [] _attributes = new String[] {"EmployeeFirstName", "EmployeeMidName", "EmployeeSurname",
     "EmployeeLBO", "EmployeeGender", "EmployeeJMBG"};
    
    
    public Employee(int id)
    {
        _employeeId = id;
        _employees.add(this);

    }
    public boolean isSatisfyCondition()
    {
        boolean satisfyGender = true;
        boolean satisfyPartime = true;
        satisfyGender = true; // postavljamo na true na pocetku.
        // prvo ispitujemo da li je pol zaposlenog jedan od selektovanih
        if ( ! StatisticsDialog.selectedGender.contains(getValue("EmployeeGender")))
            satisfyGender = false;

        if ( ! StatisticsDialog.selectedPartime.contains(getValue("EmployeeJobDetailsPartimeJob")))
            satisfyPartime = false;

        // uzimamo niz pozicija zaposlenog. Ako je neka od tih pozicija u selectedPositions,
        // tada je zaposlen u selektovanoj grupi
        String [] positions = getValue("JobTypeTitle").split(",");
        
        boolean satisfyPosition = false;
        for (String s : positions)
            if (StatisticsDialog.selectedPositions.contains(s))
            {
                satisfyPosition = true;
                break;
            }

        return satisfyGender && satisfyPosition && satisfyPartime;

    }
    // Funkcija koja popunjava vrednosti atributa zaposlenog.
    public void setValues(ResultSet rs) throws SQLException
    {
        for (String attr : _attributes)
            _values.put(attr, rs.getString(attr));

        // uzimamo datum rodjenja
        String date = DateFormat.getDateInstance().format(rs.getDate("EmployeeDateOfBirth") != null ? rs.getDate("EmployeeDateOfBirth") : new Date());
        _values.put("EmployeeDateOfBirth", date );
        
        // ubacujemo pozicije na kojima je zaposlen angazovan
        String query = "SELECT jt.JobTypeTitle, ejt.EmployeeJobTypeStartDate FROM JobType jt, EmployeeJobType ejt WHERE " +
                " jt.JobTypeID = ejt.JobTypeID AND ejt.EmployeeID = '" + _employeeId + "' AND"
                + " ejt.EmployeeJobTypeActive = '1' ; ";
        Connection  conn = Database.getConnection();
        ResultSet _rs = conn.createStatement().executeQuery(query);
        String positions = "";
        String dates = "";
        while (_rs.next())
        {
            positions += (_rs.getString("JobTypeTitle") + ",");
            Date d = _rs.getDate("EmployeeJobTypeStartDate");
            if( d != null )
            {
                dates += d.toString();
                dates += " ";
            }
        }
        int tmp = positions.lastIndexOf(",");
        if (tmp > 0)
            positions = positions.substring(0, positions.lastIndexOf(","));
        _values.put("JobTypeTitle", positions);
        _values.put("EmployeeJobTypeStartDate", dates);

        // ubacujemo predmete koje zaposleni drzi (ako je nastavno osoblje)
        query = "SELECT CourseTitle FROM Course c, EmployeeCourse ec WHERE c.CourseID = ec.CourseID AND " +
                "ec.EmployeeID = '" + _employeeId + "' ; ";
        _rs = conn.createStatement().executeQuery(query);
        String courses = "";
        while (_rs.next())
            courses += (_rs.getString("CourseTitle") + ",");
        tmp = courses.lastIndexOf(",");
        if (tmp > 0)
            courses = courses.substring(0, courses.lastIndexOf(","));
        _values.put("CourseTitle", courses);

        // Ubacujemo uzu naucnu oblast zaposlenog
        query = "SELECT ScienceDomainTitle FROM ScienceDomain sd, EmployeeCourse ec, ScienceDomainCourses sdc WHERE " +
                "sd.ScienceDomainID = sdc.ScienceDomainID AND " +
                "sdc.CourseID = ec.CourseID AND " +
                "ec.EmployeeID = '" + _employeeId + "' ;";
        String scienceDomain = "";
        _rs = conn.createStatement().executeQuery(query);
        if ( _rs.first() )
        {
            scienceDomain = _rs.getString("ScienceDomainTitle");
        }
        _values.put( "ScienceDomainTitle", scienceDomain );

        
        // Racunamo ukupan staz.
        // Prvo uzimamo prethodni staz.
        int workYears  = rs.getInt("EmployeeWorkingYears");
        int workMonths = rs.getInt("EmployeeWorkingMonths");
        int workDays = rs.getInt("EmployeeWorkingDays");

        // potom, uzimamo tekuci datum i datum kad se zaposlio na SF
        Date dt = rs.getDate("EmployeeJobDate");
        Date now = new Date();

        // uzimamo staz na SF, danasnji datum - datum kad je poceo na SF
        long diff = now.getTime() - dt.getTime();
        long delay = getTotalStagnation();
        // oduzimamo od ukupnog staza, vreme stagnacije
        diff -= delay;
        long daysDiff   = (diff / (1000L*60L*60L*24L));

        // preracunavamo razliku u danima u dane, mesece i godine.

        long yearsDiff  = daysDiff / 365;
        long monthsDiff = (daysDiff % 365) / 30;
        long restDays = (daysDiff % 365) % 30;

        long totalWorkYears  = workYears + yearsDiff;
        int totalWorkMonths  = (int) (workMonths + monthsDiff);
        int totalWorkDays = (int) (workDays + restDays);

        if (totalWorkDays >= 30)
        {
            totalWorkMonths += 1;

            totalWorkDays %= 30;
        }

        // if checksum is greater than 12, increase year by 1
        if (totalWorkMonths >= 12)
        {
            totalWorkYears += 1;
            totalWorkMonths = (totalWorkMonths % 12);
        }
        // formiramo string od rezultata i upisujemo u hes mapu kao employeetotalworktime
        String employeeTotalWorkTime = "" + totalWorkYears + "god. " + totalWorkMonths + "mes. " + totalWorkDays + "dana. ";
        _values.put("EmployeeTotalWorkTime", employeeTotalWorkTime);

        // uzimamo podatke o angazovanju zaposlenog: pola radnog vremena, i tako...
        query = "SELECT ejd.EmployeeJobDetailsPartimeJob, ejd.EmployeeJobDetailsPartimeJobPercent FROM EmployeeJobDetails ejd WHERE "
                + " ejd.EmployeeID = '" + _employeeId + "' ;";
        _rs = conn.createStatement().executeQuery(query);
        if( _rs.first() )
        {
            int partTime = _rs.getInt("EmployeeJobDetailsPartimeJob");
            int partTimePercent = _rs.getInt("EmployeeJobDetailsPartimeJobPercent");

            _values.put("EmployeeJobDetailsPartimeJob", "" + partTime );

            _values.put("EmployeeJobDetailsPartimeJobPercent", "" + ( partTime != 0 ? partTimePercent : 100 ) );
            
        }
        // ako nisu uneti podaci o angazovanju zaposlenog, ubacujemo 0, kao fullTime indikator
        // da je zaposleni fullTIme i 100% angazovanje ima
        else
        {
            _values.put("EmployeeJobDetailsPartimeJob", "" + 0 );
            _values.put("EmployeeJobDetailsPartimeJobPercent", "" + 100 );
        }

        _rs.close();
        conn.close();
        
        
    }

    // f-ja koja vraca vrednost atributa zaposlenog
    public String getValue(String attr)
    {
        if (_values.containsKey(attr))
            return _values.get(attr);
        return "";
    }

    private long getTotalStagnation()
    {
        String query = "SELECT EmployeeWorkStagnationID, EmployeeWorkStagnationStartDate as sdate, " +
                "EmployeeWorkStagnationEndDate as edate FROM EmployeeWorkStagnation WHERE EmployeeID = '" + _employeeId + "' ;";

        long delay = 0; // ukupna pauza u milisekundama
        Date sdate = new Date();
        Date edate = new Date();
        try
        {
            Connection  conn = Database.getConnection();
            ResultSet rs = conn.createStatement().executeQuery(query);
            while(rs.next())
            {
                sdate = rs.getDate("sdate");
                edate = rs.getDate("edate");
                delay += (edate.getTime() - sdate.getTime());
            }
            rs.close();
            conn.close();
        }
        catch (SQLException e) {e.printStackTrace();}
        //System.out.println("Calculating for " + _currentEmployee);
        return delay;
    }
    @Override
    public String toString()
    {
        String s = "";
        Iterator i = _values.keySet().iterator();
        while(i.hasNext())
            s += ( _values.get(i.next()) + " ");
        return s;
    }

    public static void reset()
    {
        _employees.clear();
    }

    public static void loadEmployees()
    {
        Employee.reset();

        String query = "SELECT * FROM Employee ORDER BY EmployeeSurname, EmployeeFirstName";
        try
        {
            Connection  conn = Database.getConnection();
            ResultSet rs = conn.createStatement().executeQuery(query);
            //System.out.println("=============================================");
            while(rs.next())
            {
                Employee e = new Employee(rs.getInt("EmployeeID"));
                e.setValues(rs);
                //System.out.println("Retrieved: " + rs.getString("EmployeeSurname") );
            }
            rs.close();
            conn.close();
        }
        catch(SQLException e) {e.printStackTrace();}
    }

}
